package jch.learn.java.advanced.chapter2_InputAndOutput;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Objects;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipTest {

    public static void main(String[] args) throws IOException {
        addZip();
        String zipName = "test.zip";
        showContents(zipName);
        System.out.println("---");
//        showContents2(zipName);
    }

//    private static void showContents2(String zipName) throws IOException {
//        FileSystem fs = FileSystems.newFileSystem(Paths.get(zipName), null);
//        Files.walkFileTree(fs.getPath("/"), new SimpleFileVisitor<Path>() {
//            @Override
//            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
//                System.out.println(file);
//                for (String line : Files.readAllLines(file, StandardCharsets.UTF_8)) {
//                    System.out.println("  " + line);
//                }
//                return FileVisitResult.CONTINUE;
//            }
//        });
//    }

    private static void showContents(String zipName) throws IOException {
        try (ZipInputStream zin = new ZipInputStream(new FileInputStream(zipName))) {
            ZipEntry entry;
            while ((entry = zin.getNextEntry()) != null) {
                System.out.println(entry.getName());
                Scanner in = new Scanner(zin, StandardCharsets.UTF_8.name());
                while (in.hasNextLine()) {
                    System.out.println("  " + in.nextLine());
                }
                zin.closeEntry();
            }
        }
    }

    private static void addZip() throws IOException {
        FileOutputStream fout = new FileOutputStream("test.zip");
        ZipOutputStream zout = new ZipOutputStream(fout);
        File files = new File("java-core-technology-advanced/src/main/resources/chapter2");
        for (File file : Objects.requireNonNull(files.listFiles())) {
            ZipEntry ze = new ZipEntry(file.getPath());
            zout.putNextEntry(ze);
            zout.closeEntry();
        }
        zout.close();
    }
}
